<?php

namespace App\Http\Controllers\Web;

use App\Models\Goods;
use App\Models\GoodType;
use App\Models\MemberLevel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class GoodsController extends Controller
{

    /**
     * 列表
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
        	
        	$sortName = $request->post("sortName");    //排序列名
			$sortOrder = $request->post("sortOrder");   //排序（desc，asc）
			$pageNumber = $request->post("pageNumber");  //当前页码
			$pageSize = $request->post("pageSize");   //一页显示的条数
			$start = ($pageNumber-1)*$pageSize;   //开始位置
			$search = $request->post("search",'');  //搜索条件
			
			$total = Goods::where('status', '=', 0);
			$rows = Goods::where('status', '=', 0);
			
	        if(trim($search)){
	        	$total->where(function ($query) use ($search) {
                    $query->where('goods_name', 'LIKE', '%' . $search . '%');
                });
	        	$rows->where(function ($query) use ($search) {
                    $query->where('goods_name', 'LIKE', '%' . $search . '%');
                });
	        }
	        
	        $data['total'] = $total->count();
	        $data['rows'] = $rows->skip($start)->take($pageSize)
					        ->orderBy($sortName, $sortOrder)
					        ->get();
	        
	        $level = MemberLevel::find((int)auth('web')->user()->level);

            foreach ($data['rows'] as $v){
                //一口价
                if($v->price_type == 1){
                    $v->dlprice = $v->price;
                }elseif($v->price_type == 0){
                    $v->dlprice =  number_format($v->price*$level->discount/100,2);
                }
            }
	        
	        return response()->json($data);
        }
        return view('web.goods.index');
    }

    /**
     * 购买
     *
     * @return \Illuminate\Http\Response
     */
    public function buy($id)
    {
        $goods = Goods::find((int)$id);
        $level = MemberLevel::find((int)auth('web')->user()->level);

        if($goods->price_type == 1){
            $agentPrice = $goods->price;
        }elseif($goods->price_type == 0){
            $agentPrice = round($goods->price*$level->discount/100,2);
        }

        $goods->agentPrice = $agentPrice;
        $goods->discount = $level->discount;
        $goods->discountNanem = $level->name;
        $data['goods'] = $goods;
        return view('web.goods.buy',$data);
    }

    /**
     * 新增
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data["name"]   = $request->input("name");
        $data["pic"]    = $request->input("thum");
        $data["price"]  = $request->input("price");
        $data["type"]   = $request->input("type");
        $data["body"]   = $request->input("body");
        $data["price_type"] = $request->input("price_type");
        Goods::create($data);
        return redirect('/admin/goods')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * 修改
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = Goods::find((int)$id);
        if (!$data) return redirect('/admin/goods')->withErrors("找不到该商品!");
//        event(new \App\Events\userActionEvent('\App\Models\Admin\AdminUser', $user->id, 3, '编辑了用户' . $user->name));

        return view('admin.goods.edit', $data);
    }

    /**
     * 更新
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data["name"]   = $request->input("name");
        $data["pic"]    = $request->input("thum");
        $data["price"]  = $request->input("price");
        $data["type"]   = $request->input("type");
        $data["body"]   = $request->input("body");
        $data["price_type"] = $request->input("price_type");
        $res = Goods::where("id","=",$id)->update($data);
        if($res){
            $msg = "更新成功！";
        }else{
            $msg = "更新失败！";
        }
        return redirect('/admin/goods')->withSuccess($msg);
    }

    /**
     * 删除
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $tag = Goods::find((int)$id);
        if($tag->delete()){
            return redirect()->back()->withSuccess("删除成功");
        }

    }
    
    /**
     *商品详情 
	 *
     */
    public function details(Request $request, $id){
    	
    	$goods = Goods::find((int)$id);
        $level = MemberLevel::find((int)auth('web')->user()->level);

        if($goods->price_type == 1){
            $agentPrice = $goods->price;
            $discount = 100;
        }elseif($goods->price_type == 0){
        	$discount = $level->discount;
            $agentPrice = round($goods->price*$level->discount/100,2);
        }
        
    	$data['discount'] = $discount; //折扣
    	$data['agentPrice'] = $agentPrice;  //打折后的价格
    	
    	
		$arr = json_decode($goods['goods_version'],true);
		//判断是否有商品规格
        if(count($arr)>0){
	        foreach($arr as $k=>$v){
	        	$array_arr['id'] = $goods->id;
	        	$array_arr['goods_id'] = $goods->id;
	        	$array_arr['goods_version'] = $v['goods_version'];
	        	$array_arr['time_length'] = $v['time_length'];
	        	$array_arr['unit'] = $v['unit'];
	        	$array_arr['originalPrice'] = $v['originalPrice'];
				$array_data[$k] = $array_arr;
	        }   
	        $data['good_type'] = $array_data;
	    }else{
	    	$data['good_type'][0] = array(
	        	"goods_version"=>"初始版",
	        	"time_length"=>1,
	        	"unit"=>$this->getUnit($goods->long),
	        	"originalPrice"=>$agentPrice
	        );
	    }
		
		foreach($data['good_type'] as $key=>$val){
    		$data['good_type'][$key]['unit'] = $this->getUnit($val['unit']);
    	}
    	
    	$data['goods']=Goods::where('id','=',$id)->where('status','=',0)->first();
    	return view('web.goods.details',$data);
    }
    /**
     * 判断时间 
     */
    public function getUnit($obj){
    	if($obj==0){
    		return '永久';
    	}else if($obj==2){
    		return '月';
    	}else if($obj==3){
    		return '日';
    	}else{
    		return '年';
    	}
    }
    
}
